package main

import (
	"flag"
	"fmt"
	"os"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

var (
	client       *oss.Client
	AccessKey    = os.Getenv("ALI_AK")
	AccessSecret = os.Getenv("ALI_SK")
	Endpoint     = os.Getenv("ALI_OSS_ENDPOINT")
	BucketName   = os.Getenv("ALI_BUCKET_NAME")
	uploadFile   = ""
	help         = false
)

func upload(file_path string) error {
	client, err := oss.New(Endpoint, AccessKey, AccessSecret)
	if err != nil {
		return err
	}
	bucket, err := client.Bucket(BucketName)
	if err != nil {
		return err
	}
	if err := bucket.PutObjectFromFile(file_path, file_path); err != nil {
		return err
	}

	downloadURL, err := bucket.SignURL(file_path, oss.HTTPGet, 60*60*24)
	if err != nil {
		return err
	}
	fmt.Printf("文件下载地址%s", downloadURL)
	return nil

}
func validate() error {
	if Endpoint == "" || AccessKey == "" || AccessSecret == "" {
		fmt.Println("please set env ALI_AK,ALI_SK,ALI_OSS_ENDPOINT")
		usage()
		os.Exit(1)
	}
	if uploadFile == "" {
		fmt.Println("please set env UPLOAD_FILE")
		usage()
		os.Exit(1)
	}

	return nil
}

func loadParams() {
	flag.BoolVar(&help, "h", false, "show help")
	flag.StringVar(&uploadFile, "file", "", "file to upload")
	flag.Parse()
	if help {
		usage()
		os.Exit(0)
	}
}
func usage() {
	fmt.Fprintf(os.Stderr, "usage: [-h] -f <upload_file>")
	flag.PrintDefaults()
}

func main() {
	loadParams()

	if err := validate(); err != nil {
		fmt.Println("validate failed", err)
		os.Exit(1)
	}
	if err := upload(uploadFile); err != nil {
		fmt.Println("upload failed", err)
		os.Exit(1)
	}

}
